package com.example.jimuyutabletcontrol.location;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;

import com.example.jimuyutabletcontrol.MapApplication;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: HDX
 * @date: 2020\5\27 0027
 */
public class LocationProvider implements ILocationProvider {

    private static ILocationProvider locationProvider;

    public synchronized static ILocationProvider getInstance() {
        if (null == locationProvider) {
            locationProvider = new LocationProvider();
        }
        return locationProvider;
    }

    /**
     * 经纬度外部接口
     */
    private List<LocationInterface> locationOutSideInterfaces;

    /**
     * 经纬度管理对象
     */
    private LocationManager locationManager;

    /**
     * 经纬度内部接口
     */
    private LocationListener locationInsideListener;

    private String currentProvider = LocationManager.GPS_PROVIDER;

    private double values[] = new double[3];

    private final String valueLock = "valueLock";

    private final String lastLocationLock = "lastLocationLock";


    private LocationProvider() {
        locationOutSideInterfaces = new ArrayList<>();
    }

    private Timer timer;

    private TimerTask task;

    @Override
    public void setLocationOutSideInterface(LocationInterface locationOutSideInterface) {
        if (null == locationOutSideInterface) return;
        if (null == locationOutSideInterfaces) {
            locationOutSideInterfaces = new ArrayList<>();
        }
        if (locationOutSideInterfaces.contains(locationOutSideInterface)) return;
        locationOutSideInterfaces.add(locationOutSideInterface);
    }

    @Override
    public void removeLocationOutSideInterface(LocationInterface locationOutSideInterface) {
        if (null == locationOutSideInterface || null == locationOutSideInterfaces || locationOutSideInterfaces.size() == 0)
            return;
        if (!locationOutSideInterfaces.contains(locationOutSideInterface)) return;
        locationOutSideInterfaces.remove(locationOutSideInterface);
    }

    @Override
    public void removeAllLocationOutSideInterface() {
        if (null == locationOutSideInterfaces || locationOutSideInterfaces.size() == 0) return;
        locationOutSideInterfaces.clear();
    }

    /**
     * 开始定位
     */
    @SuppressLint("MissingPermission") //
    @Override
    public void startLocation() {
        createListener();
        locationManager = (LocationManager) MapApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
        if (null == locationManager) return;
        locationManager.removeUpdates(locationInsideListener);
        Criteria criteria = new Criteria();//
        criteria.setAccuracy(Criteria.ACCURACY_FINE);//设置定位精准度
        criteria.setAltitudeRequired(true);//是否要求海拔
        criteria.setBearingRequired(true);//是否要求方向
        criteria.setCostAllowed(true);//是否要求收费
        criteria.setSpeedRequired(true);//是否要求速度
        criteria.setPowerRequirement(Criteria.POWER_HIGH);//设置相对省电
        criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);//设置方向精确度
        criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);//设置速度精确度
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);//设置水平方向精确度
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);//设置垂直方向精确度
        currentProvider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(TextUtils.isEmpty(currentProvider) ? LocationManager.GPS_PROVIDER : currentProvider,
                1000, 0, locationInsideListener, Looper.myLooper());
//        sendLocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));

//        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationInsideListener);
//        sendLocation(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
//        locationManager.removeUpdates(locationInsideListener);
//        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 20, locationInsideListener);
//        sendLocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
    }

    /**
     * 经纬度发送
     *
     * @param location
     */
    private void sendLocation(Location location) {
        if (null != location && null != locationOutSideInterfaces && locationOutSideInterfaces.size() > 0) {
            for (LocationInterface locationInterface : locationOutSideInterfaces) {
                locationInterface.showLocation(location);
            }
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void stopLocation() {
        if (null != locationManager && null != locationInsideListener) {
            locationManager.removeUpdates(locationInsideListener);
            locationManager = null;
            locationInsideListener = null;
        }
        if (null != locationOutSideInterfaces) {
            locationOutSideInterfaces.clear();
            locationOutSideInterfaces = null;
        }
    }

    public double[] getValue() {
        synchronized (valueLock) {
            if (null == locationManager) {
                locationManager = (LocationManager) MapApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
            }
            if (null != locationManager) {
                @SuppressLint("MissingPermission") final Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    values[0] = location.getLongitude();
                    values[1] = location.getLatitude();
                    values[2] = location.getAccuracy();
                }
            }
            return values;
        }
    }

    /**
     * 获取最新位置信息
     *
     * @return
     */
    @Override
    public Location getLastLocation() {
        synchronized (lastLocationLock) {
            if (null == locationManager) {
                locationManager = (LocationManager) MapApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
            }
            if (null != locationManager) {
                @SuppressLint("MissingPermission")
                Location location = locationManager.getLastKnownLocation(currentProvider);
                return location;
            } else return null;
        }
    }

    /**
     * 创建内部接口实例
     */
    private void createListener() {
        if (null != locationInsideListener) return;
        locationInsideListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                sendLocation(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                switch (status) {
                    //GPS状态为可见时
                    case android.location.LocationProvider.AVAILABLE:
                        break;
                    //GPS状态为服务区外时
                    case android.location.LocationProvider.OUT_OF_SERVICE:
                        //GPS状态为暂停服务时
                    case android.location.LocationProvider.TEMPORARILY_UNAVAILABLE:
//                        startLocation();
                        break;
                }
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
    }

}
